package com.returnsoft.softphone.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;

import com.returnsoft.security.exception.SecurityExcepcion;
import com.returnsoft.softphone.dto.AgentDto;
import com.returnsoft.softphone.dto.SessionTypeDto;
import com.returnsoft.softphone.exception.CCenterExcepcion;
import com.returnsoft.softphone.service.AgentInterface;
import com.returnsoft.softphone.service.SessionTypeInterface;
import com.returnsoft.util.Util;

@ManagedBean
@ViewScoped
public class AgentPanelController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private List<SelectItem> sessionTypes;

	public AgentPanelController() {
		System.out.println("Ingreso a agentPanelController");
	}

	public void beforeAgentPanel() {
		System.out.println("ingreso a beforeAgentPanel");
		try {

			SessionBean session = (SessionBean) FacesContext
					.getCurrentInstance().getExternalContext().getSessionMap()
					.get("sessionBean");
			String sessionTypeSelected = session.getSessionTypeSelected();
			Integer agentId = session.getAgentId();
			if (sessionTypeSelected == null || sessionTypeSelected.equals("")) {
				// BUSCA AGENT
				HttpServletRequest request = (HttpServletRequest) FacesContext
						.getCurrentInstance().getExternalContext().getRequest();
				String host = request.getRemoteAddr();
				AgentInterface agentService = (AgentInterface) new InitialContext(
						Util.getInitProperties())
						.lookup("java:global/CCenterEAR/CCenterEJB/AgentBean"
								+ "!com.returnsoft.softphone.service.AgentInterface");
				AgentDto agent = agentService.doLogin(agentId, host);
				System.out.println("sessiontypeselected.........."+agent.getStateSelected());
				System.out.println("sessiontypeselected.........."+agent.getStateSelected());
				System.out.println("sessiontypeselected.........."+agent.getStateSelected());
				System.out.println("sessiontypeselected.........."+agent.getStateSelected());
				System.out.println("sessiontypeselected.........."+agent.getStateSelected());
				System.out.println("sessiontypeselected.........."+agent.getStateSelected());
				session.setSessionTypeSelected(agent.getStateSelected());
				FacesContext.getCurrentInstance().getExternalContext()
						.getSessionMap().put("sessionBean", session);
				FacesMessage msg = new FacesMessage("Inicio como "
						+ agent.getStateSelected(), null);
				msg.setSeverity(FacesMessage.SEVERITY_INFO);
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}

			if (sessionTypes == null || sessionTypes.size() == 0) {
				System.out.println("Ingresa a buscar sessionTypes");
				System.out.println("el agentId: "+agentId);
				SessionTypeInterface sessionTypeService = (SessionTypeInterface) new InitialContext(
						Util.getInitProperties())
						.lookup("java:global/CCenterEAR/CCenterEJB/SessionTypeBean"
								+ "!com.returnsoft.softphone.service.SessionTypeInterface");
				sessionTypes = new ArrayList<SelectItem>();
				List<SessionTypeDto> sessionTypesDto = sessionTypeService
						.findTypesByAgent(agentId);
				System.out.println("sessionTypes encontrados: " +sessionTypesDto.size() );
				for (SessionTypeDto sessionTypeDto : sessionTypesDto) {
					SelectItem sessionTypeItem = new SelectItem();
					sessionTypeItem.setValue(sessionTypeDto.getCode());
					sessionTypeItem.setLabel(sessionTypeDto.getName());
					sessionTypes.add(sessionTypeItem);
				}
			}

		} catch (Exception e) {
			if (!(e instanceof CCenterExcepcion) && !(e instanceof SecurityExcepcion)) {
				e.printStackTrace();	
			}
			FacesMessage msg = new FacesMessage(e.getMessage(), e.getMessage());
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage(null, msg);

		}
	}

	public void changeState() {

		System.out.println("ingreso a changeState");

		try {

			// OBTIENE LA SESSION
			SessionBean session = (SessionBean) FacesContext
					.getCurrentInstance().getExternalContext().getSessionMap()
					.get("sessionBean");
			Integer agentId = session.getAgentId();
			String sessionTypeSelected = session.getSessionTypeSelected();
			
			HttpServletRequest request = (HttpServletRequest) FacesContext
					.getCurrentInstance().getExternalContext().getRequest();
			String host = request.getRemoteAddr();

			AgentInterface agentService = (AgentInterface) new InitialContext(
					Util.getInitProperties())
					.lookup("java:global/CCenterEAR/CCenterEJB/AgentBean"
							+ "!com.returnsoft.softphone.service.AgentInterface");
			AgentDto agent = agentService.changeState(agentId, host,
					sessionTypeSelected);
			if (sessionTypeSelected.equals("logout")) {
				FacesContext.getCurrentInstance().getExternalContext()
						.invalidateSession();
				FacesMessage msg = new FacesMessage("Finalizo ", null);
				msg.setSeverity(FacesMessage.SEVERITY_INFO);
				FacesContext.getCurrentInstance().addMessage(null, msg);

				FacesContext context = FacesContext.getCurrentInstance();
				NavigationHandler navigationHandler = context.getApplication()
						.getNavigationHandler();
				navigationHandler.handleNavigation(context, null, "login"
						+ "?faces-redirect=true");

			} else {
				// ACTUALIZA LA SESION
				session.setSessionTypeSelected(agent.getStateSelected());
				FacesMessage msg = new FacesMessage("Cambio a "
						+ agent.getStateSelected(), null);
				msg.setSeverity(FacesMessage.SEVERITY_INFO);
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
		} catch (Exception e) {
			if (!(e instanceof CCenterExcepcion) && !(e instanceof SecurityExcepcion)) {
				e.printStackTrace();	
			}
			FacesMessage msg = new FacesMessage(e.getMessage(),
					e.getMessage());
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
	}

	public void updateStatus() {
		System.out.println("ingreso a update status");
		FacesMessage msg = new FacesMessage("Actualizo correctamente", null);
		msg.setSeverity(FacesMessage.SEVERITY_INFO);
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public List<SelectItem> getSessionTypes() {
		return sessionTypes;
	}

	public void setSessionTypes(List<SelectItem> sessionTypes) {
		this.sessionTypes = sessionTypes;
	}

}
